<template>
  <div class="menu-container">
    <el-button type="primary" @click="handleClick(null, 0, '新增菜单')"
      >新增</el-button
    >
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px">
      <el-form
        label-position="left"
        label-width="80px"
        :model="menuForm"
        :rules="rules"
        ref="menuForm"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item prop="type" label="菜单类型">
              <el-radio
                :disabled="formType === 1"
                v-for="item in sysMenuTyps"
                :key="item.value"
                v-model="menuForm.type"
                :label="item.value"
                >{{ item.label }}</el-radio
              >
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="parents" label="上级菜单">
              <el-cascader
                :disabled="formType === 1"
                placeholder="根目录"
                :options="pageMenus"
                v-model="menuForm.parents"
                :props="{ checkStrictly: true, label: 'title', value: 'id' }"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item v-if="menuForm.type !== '2'" label="菜单图标">
              <el-popover
                :disabled="formType === 1"
                placement="bottom-start"
                width="460"
                trigger="click"
                @show="$refs['iconSelect'].reset()"
              >
                <IconSelect ref="iconSelect" @selected="selected" />
                <el-input
                  :disabled="formType === 1"
                  slot="reference"
                  v-model="menuForm.icon"
                  placeholder="点击选择图标"
                  readonly
                >
                  <svg-icon
                    v-if="menuForm.icon"
                    slot="prefix"
                    :icon-class="menuForm.icon"
                    class="el-input__icon"
                    style="height: 32px; width: 16px"
                  />
                  <i
                    v-else
                    slot="prefix"
                    class="el-icon-search el-input__icon"
                  />
                </el-input>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="title">
              <el-input
                :disabled="formType === 1"
                v-model="menuForm.title"
                placeholder="请输入内容"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="路由地址" prop="path">
              <el-input
                :disabled="formType === 1"
                v-model="menuForm.path"
                placeholder="请输入内容"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="menuForm.type == 2"
              label="权限标识"
              prop="sign"
            >
              <el-input
                :disabled="formType === 1"
                v-model="menuForm.sign"
                placeholder="请输入内容"
                clearable
              />
            </el-form-item>
          </el-col>
          <div>
            <el-col :span="12">
              <el-form-item
                v-if="
                  (menuForm.type === '0' && menuForm.parents.length > 0)
                "
                prop="component"
                label="组件路径"
              >
                <el-input
                  :disabled="formType === 1"
                  v-model="menuForm.component"
                  placeholder="请输入内容"
                  clearable
                />
              </el-form-item>
            </el-col>
          </div>
          <el-col :span="12">
            <el-form-item v-if="menuForm.type !== '2'" label="显示状态">
              <el-radio-group v-model="menuForm.visible">
                <el-radio
                  :disabled="formType === 1"
                  v-for="dict in visibleOptions"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单状态">
              <el-radio-group v-model="menuForm.status">
                <el-radio
                  :disabled="formType === 1"
                  v-for="dict in statusOptions"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否外链" v-if="menuForm.type !== '2'">
              <el-radio-group
                :disabled="formType === 1"
                v-model="menuForm.isFrame"
              >
                <el-radio label="0">是</el-radio>
                <el-radio label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="sort" label="排序">
              <el-input-number
                :disabled="formType === 1"
                v-model="menuForm.sort"
                :min="1"
                label="描述文字"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          v-if="formType !== 1"
          :loading="loading"
          type="primary"
          @click="confirmHandel('menuForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-table
      :data="pagination.menuDatas"
      row-key="id"
      border
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="title" label="标题"></el-table-column>
      <el-table-column prop="path" label="路由地址"></el-table-column>
      <el-table-column prop="type" label="类型">
        <template slot-scope="scope">
          <el-tag disable-transitions>{{
            getMenuTypeLabel(scope.row.type)
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序"></el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.status === '0' ? 'success' : 'danger'"
            disable-transitions
            >{{ scope.row.status === "0" ? "启用" : "禁用" }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150px">
        <template slot-scope="scope">
          <el-button
            @click="handleClick(scope.row, 1, '查看菜单')"
            type="text"
            size="small"
            >查看</el-button
          >
          <el-button
            @click="handleClick(scope.row, 2, '编辑菜单')"
            type="text"
            size="small"
            >编辑</el-button
          >
          <el-button @click="delMenu(scope.row)" type="text" size="small"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.currentPage"
      :page-sizes="pagination.pageSizeChoose"
      :page-size="pagination.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
    ></el-pagination>
  </div>
</template>

<script>
import {
  getPaginationList,
  getMenuDetailVoList,
  add,
  del,
  getDetails,
  update,
} from "@/api/admin/permission";
import IconSelect from "@/components/IconSelect";
import { cascaderDisabledSelf } from "@/utils/common";

export default {
  name: "Menu",
  components: { IconSelect },
  created() {
    this.getPaginationMenus();
    this.getSysMenuTyps();
    this.getDictList({ type: "sys_common_status" }).then((res) => {
      this.statusOptions = res.data;
    });
    this.getDictList({ type: "sys_show_hide" }).then((res) => {
      this.visibleOptions = res.data;
    });
  },
  data() {
    return {
      formType: 0,
      loading: false,
      types: [],
      pageMenus: [],
      dialogVisible: false,
      dialogTitle: "",
      sysMenuTyps: [],
      statusOptions: [],
      visibleOptions: [],
      menuForm: {
        type: "0",
        visible: "0",
        isFrame: "1",
        title: "",
        sign: "",
        sort: 1,
        icon: "",
        parents: [],
        parentId: 0,
        component: "",
        path: "",
        status: "0",
      },
      pagination: {
        currentPage: 1,
        pageSize: 10,
        pageSizeChoose: [5, 10, 15, 20],
        total: 0,
        menuDatas: [],
      },
      rules: {
        sign: [{ required: true, message: "请输入标识", trigger: "blur" }],
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        component: [
          { required: true, message: "请输入组件路径", trigger: "blur" },
        ],
        path: [{ required: true, message: "请输入请求路径", trigger: "blur" }],
      },
    };
  },

  watch: {
    dialogVisible: function () {
      if (this.dialogVisible === true) {
        this.getPageMenus();
      } else {
        this.menuForm = {
          type: "0",
          visible: "0",
          isFrame: "1",
          title: "",
          sign: "",
          sort: 1,
          icon: "",
          parents: [],
          parentId: 0,
          component: "",
          path: "",
          status: "0",
        };
        this.menuForm.icon = null;
      }
    },
  },
  methods: {
    // 选择图标
    selected(name) {
      this.menuForm.icon = name;
    },
    getSysMenuTyps() {
      const params = {
        type: "sys_menu_type",
      };
      this.getDictList(params).then((res) => {
        this.sysMenuTyps = res.data;
      });
    },
    delMenu(menu) {
      this.$confirm(
        '是否确认删除菜单名为"' + menu.title + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return del(menu.id);
        })
        .then(() => {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          this.getPaginationMenus();
        });
    },
    addMenu() {
      this.getParentId();
      add(this.menuForm)
        .then(() => {
          this.$message({
            message: "新增成功",
            type: "success",
          });
          this.dialogVisible = false;
          this.loading = false;
          this.getPaginationMenus();
        })
        .catch(() => {
          this.loading = false;
        });
    },
    getParentId() {
      if (this.menuForm.parents.length > 0) {
        this.menuForm.parentId = this.menuForm.parents[
          this.menuForm.parents.length - 1
        ];
      }
    },
    updataMenu() {
      this.getParentId();
      update(this.menuForm)
        .then(() => {
          this.$message({
            message: "修改成功",
            type: "success",
          });
          this.dialogVisible = false;
          this.loading = false;
          this.getPaginationMenus();
        })
        .catch(() => {
          this.loading = false;
        });
    },
    confirmHandel(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.formType === 0) {
            this.addMenu();
          } else if (this.formType === 2) {
            this.updataMenu();
          }
          this.loading = true;
        }
      });
    },
    getMenuTypeLabel(value) {
      let ss = "";
      this.sysMenuTyps.forEach((item) => {
        if (item.value === value) {
          ss = item.label;
        }
      });
      return ss;
    },
    getPageMenus() {
      getMenuDetailVoList().then((res) => {
        this.pageMenus = res.data;
        cascaderDisabledSelf(this.pageMenus, this.menuForm);
      });
    },
    getPaginationMenus() {
      const params = {
        pageSize: this.pagination.pageSize,
        pageIndex: this.pagination.currentPage,
      };
      getPaginationList(params).then((res) => {
        this.pagination.menuDatas = res.data.records;
        this.pagination.total = res.data.total;
      });
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val;
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
    },
    handleClick(data, type, title) {
      if (type !== 0) {
        getDetails(data.id).then((response) => {
          this.menuForm = response.data;
        });
      }
      this.dialogTitle = title;
      this.formType = type;
      this.dialogVisible = true;
    },
  },
};
</script>

<style lang="scss" scoped>
</style>